<template>
  <div class="login-container">
    <!-- 顶部导航 -->
    <van-nav-bar class="top" title="登录" />
    <!-- 表单 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="mobile"
        name="mobile"
        label="手机号"
        placeholder="请输入手机号"
        required
        :rules="[
          { required: true, message: '请输入手机号' },
          {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '请输入正确的手机号'
          }
        ]"
      />
      <van-field
        v-model="code"
        name="code"
        label="验证码"
        placeholder="验证码"
        required
        :rules="[
          { required: true, message: '请填写验证码' },
          { pattern: /\d[6]/, message: '验证码错误' }
        ]"
      />
      <div style="margin: 16px;">
        <van-button
          :loading="isLoading"
          :disabled="isLoading"
          loading-text="加载中..."
          round
          block
          type="info"
          native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { userLogin } from '../../api/login.js'
import { saveToken } from '../../utils/token'

export default {
  name: 'login',
  created () {
    // console.log(userLogin)
    // console.log(getToken())
  },
  data () {
    return {
      mobile: '15919740939',
      code: '246810',
      isLoading: false
    }
  },
  methods: {
    onSubmit (values) {
      // console.log('submit', values)
      this.isLoading = true
      this.isDisabled = true
      userLogin(values)
        .then(res => {
          console.log(res)
          this.$toast.success('成功')
          this.isLoading = false
          saveToken(res.data.data)
          // 根据url中的地址，决定跳转的路径
          if (this.$route.query.back) {
            // 原路返回
            this.$router.push({ path: this.$route.query.back })
          } else {
            // 没有值
            this.$router.push({ path: '/home' })
          }
        })
        .catch(errRes => {
          console.log(errRes)
          this.$toast.fail('失败')
          this.isLoading = false
        })
    }
  }
}
</script>

<style lang="less">
.login-container {
  .top {
    background-color: #3196fa;
    .van-nav-bar__title {
      color: white;
    }
  }
}
</style>
